package com.starryx.driverschool.controller;

import com.starryx.driverschool.po.Student;
import com.starryx.driverschool.service.StudentService;
import com.starryx.driverschool.service.TeacherService;
import com.starryx.driverschool.vo.StudentQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.List;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @Autowired
    private TeacherService teacherService;

    @GetMapping("/student")
    public String student(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC)
    Pageable pageable,
    Model model){
        model.addAttribute("page", studentService.listStudent(pageable));
        return "student";
    }

    @GetMapping("/student/input")
    public String input(Model model){
        model.addAttribute("student", new Student());
        model.addAttribute("teachers", teacherService.listTeacher());
        return "student-input";
    }

    @GetMapping("/student/input/{id}")
    public String input(@PathVariable Long id, Model model){
        model.addAttribute("student", studentService.getStudent(id));
        model.addAttribute("teachers", teacherService.listTeacher());
        return "student-input";
    }

    @PostMapping("/student/save")
    public String save(@Valid Student student,
                       BindingResult result,
                       RedirectAttributes attributes){
        Student student1 = studentService.getStudentByNo(student.getNo());
        if(student1 != null){
            result.rejectValue("no", "noError", "不能添加重复的学员");
        }
        if (result.hasErrors()){
            return "student-input";
        }
        Student stu = studentService.saveStudent(student);
        if(stu == null){
            attributes.addFlashAttribute("message", "新增失败");
        }else{
            attributes.addFlashAttribute("message", "新增成功");
        }
        return "redirect:/student";
    }

    @PostMapping("/student/update")
    public String update(@Valid Student student,
                       BindingResult result,
                       RedirectAttributes attributes){
        Student student1 = studentService.getStudentByNo(student.getNo());
        if(student1 != null && !student1.getId().equals(student.getId())){
            result.rejectValue("no", "noError", "不能添加重复的学员");
        }
        if (result.hasErrors()){
            return "student-input";
        }
        Student stu = studentService.updateStudent(student.getId(), student);
        if(stu == null){
            attributes.addFlashAttribute("message", "编辑失败");
        }else{
            attributes.addFlashAttribute("message", "编辑成功");
        }
        return "redirect:/student";
    }

    // 跳转到博客列表页面
    @PostMapping("/student/search")
    public String search(@PageableDefault(size = 5, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         StudentQuery studentQuery,
                         Model model){
        model.addAttribute("page", studentService.listStudent(pageable, studentQuery));
        return "student :: studentList";       // 返回 blogList 片段，利用 thymeleaf 实现类似 ajax 那样的局部刷新
    }

    @GetMapping("/student/delete/{id}")
    public String delete(@PathVariable Long id, RedirectAttributes attributes){
        studentService.deleteStudent(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/student";
    }

    @PostMapping("/student/batchdelete")
    public String batchDelete(@RequestParam List<Long> ids, RedirectAttributes attributes){
        // 带有外键约束的表删到最后一项时会删不掉，所以要使用逻辑删除
        for(Long id : ids){
            studentService.deleteStudent(id);
        }
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/student";
    }
}
